#include "zy_at_commands.h"
#include <string.h>
#include <byte_utils.h>
#include <stdlib.h>
#include <bt_device.h>
#include "battery_monitor.h"
#include "state_of_charge.h"
#include "hfp_profile.h"
#include "logging.h"
#include "battery_monitor_config.h"
#include "handset_service.h"
#include "hfp_profile_instance.h"
 
typedef struct
{
    TaskData task;
    batteryRegistrationForm Client; 
} atCmdTaskData;
 
atCmdTaskData atCmdTask; 
 
/* vender id - product id - version- report bit */
static const char batt_enable_string[]   = "AT+XAPL=05AC-1702-0100,9\r";
static const char batt_level_string[]   = "AT+IPHONEACCEV=1,1,0\r";
uint8 last_battery_percent = 11;
#define BATT_POS   19

void HfpEnableBattReport(hfpInstanceTaskData* instance)
{
    char *at_command_data;
    if(instance->bitfields.hf_indicator_assigned_num == hf_battery_level)
    {
        /* 支持BIEV，不发送补丁指令 */
    }
    else
    {
        at_command_data = malloc(sizeof(batt_enable_string));
        uint16 voltage = appBatteryGetVoltageAverage();
        if (at_command_data)
        {
            memcpy(at_command_data, batt_enable_string, sizeof(batt_enable_string));
            HfAtCmdReqSend(instance->connection_id, sizeof(at_command_data), at_command_data);
        }
        last_battery_percent = 11;
        HfpAtCmdSendBatt(instance->connection_id, voltage);
    }

}

void HfpDisenableBattReport(hfpInstanceTaskData* instance)
{
    UNUSED(instance);
}
 
void HfpAtCmdSendBatt(uint32 connection_id, uint16 voltage_mv)
{
    char *at_command_data;
    uint8 percent = Soc_ConvertLevelToPercentage(voltage_mv);
    at_command_data = malloc(sizeof(batt_level_string));
    if (at_command_data)
    {
        DEBUG_LOG_VERBOSE("atcmd battery event: %d",percent);
        memcpy(at_command_data, batt_level_string, sizeof(batt_level_string));
        if (percent > 94)
            at_command_data[BATT_POS] = '9';
        else if (percent > 84)
            at_command_data[BATT_POS] = '8';
        else if (percent > 74)
            at_command_data[BATT_POS] = '7';
        else if (percent > 64)
            at_command_data[BATT_POS] = '6';
        else if (percent > 54)
            at_command_data[BATT_POS] = '5';
        else if (percent > 44)
            at_command_data[BATT_POS] = '4';
        else if (percent > 34)
            at_command_data[BATT_POS] = '3';
        else if (percent > 24)
            at_command_data[BATT_POS] = '2';
        else if (percent > 14)
            at_command_data[BATT_POS] = '1';
        else
            at_command_data[BATT_POS] = '0';
        if (last_battery_percent != (percent/10))
        {
            last_battery_percent = percent/10;
            HfAtCmdReqSend(connection_id, sizeof(at_command_data), at_command_data);
        }
        else
        {
            free(at_command_data);
        }
    }
}
 
bool hfpAtCmdInit(Task init_task)
{
    UNUSED(init_task);
    return TRUE;
}
